package ua.dou.loader;

import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;

import java.lang.ref.WeakReference;

/**
 * Base loader callback.
 * @see: LoaderManager.LoaderCallbacks
 * User: David Mayboroda
 */
public abstract class BaseLoaderCallback<MD> implements LoaderManager.LoaderCallbacks<Response<MD>> {

    private WeakReference<OnLoadFinishListener<MD>> listener;

    public BaseLoaderCallback(OnLoadFinishListener<MD> listener) {
        this.listener = new WeakReference<OnLoadFinishListener<MD>>(listener);
    }

    @Override
    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    public void onLoadFinished(Loader<Response<MD>> loader, Response<MD> data) {
        OnLoadFinishListener<MD> finishListener = listener.get();
        if (data != null && finishListener != null) {
           if (data.getException() != null) {
              finishListener.onLoaderException(loader.getId(), data.getException());
           } else if (data.getModel() != null) {
               finishListener.onLoaderResult(loader.getId(), data.getModel());
           }
        }
    }

    @Override
    public void onLoaderReset(Loader<Response<MD>> loader) {
      if (listener != null) {
         listener.clear();
         listener = null;
      }
    }
}
